//
//  MainViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-13.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "MainViewController.h"
#import "ResultCell.h"

#import "BluetoothViewController.h"
@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImage *tempImage = [UIImage imageNamed:@"Menu"];
    topBar = [[LRTopBar alloc]initWithTitle:@"Anyair" AndLeft:nil AndRight:tempImage];
    topBar.delegete = self;
    [self.view addSubview:topBar];
    
    AnimateTabbarView *tabbar=[[AnimateTabbarView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    if (!IOS_7) {
        tabbar.frame = CGRectMake(tabbar.frame.origin.x, [UIScreen mainScreen].bounds.size.height-20-tabbar.frame.size.height, tabbar.frame.size.width, tabbar.frame.size.height);
    }
    tabbar.delegate=self;
    [self.view addSubview:tabbar];
    
    childView = [[UIView alloc]initWithFrame:CGRectMake(0, topBar.frame.origin.y+topBar.frame.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-tabbar.frame.size.height-topBar.frame.size.height-topBar.frame.origin.y)];
    if (!IOS_7) {
        childView.frame = CGRectMake(0, topBar.frame.origin.y+topBar.frame.size.height-20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-tabbar.frame.size.height-topBar.frame.size.height-topBar.frame.origin.y-20);
    }
    [self.view addSubview:childView];
    
    firstViewController = [[EnvirViewController alloc]init];
    secondViewController = [[BournViewController alloc]init];
    thirdViewController = [[DiscoverViewController alloc]init];
    fourthViewController = [[ProductionViewController alloc]init];
    [self addChildViewController:firstViewController];
    [self addChildViewController:secondViewController];
    [self addChildViewController:thirdViewController];
    [self addChildViewController:fourthViewController];
    
    currentViewController=firstViewController;
    [childView addSubview:firstViewController.view];
    viewTag = 1;
    [self.view bringSubviewToFront:tabbar];
    
    if ([BluetoothManager createManager].senor.manager.state == CBCentralManagerStatePoweredOn) {
        if (![BluetoothManager createManager].isConnected) {
            BluetoothViewController *bv = [[BluetoothViewController alloc]init];
            bv.view.alpha = 0;
            if (!IPHONE_5) {
                bv.view.frame = CGRectMake(0, 0, 320, 568);
            }
            [self addChildViewController:bv];
            [self.view addSubview:bv.view];
            [UIView animateWithDuration:0.2 animations:^{
                bv.view.alpha = 1;
            }];
        }
    } else {
        NSLog(@"蓝牙未打开");
        [self performSelector:@selector(checkBluetoothAgain) withObject:nil afterDelay:0.5];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)checkBluetoothAgain {
    if ([BluetoothManager createManager].senor.manager.state == CBCentralManagerStatePoweredOn) {
        if (![BluetoothManager createManager].isConnected) {
            BluetoothViewController *bv = [[BluetoothViewController alloc]init];
            bv.view.alpha = 0;
            if (!IPHONE_5) {
                bv.view.frame = CGRectMake(0, 0, 320, 568);
            }
            [self addChildViewController:bv];
            [self.view addSubview:bv.view];
            [UIView animateWithDuration:0.2 animations:^{
                bv.view.alpha = 1;
            }];
        }
    }
}

#pragma mark - tabbar代理
-(void)FirstBtnClick{
    
    if(viewTag==1)
        return;
    [self hiddenSearch];
    [self transitionFromViewController:currentViewController toViewController:firstViewController duration:0 options:0 animations:^{
    }  completion:^(BOOL finished) {
        currentViewController=firstViewController;
        viewTag=1;
        
    }];
}
-(void)SecondBtnClick{
    if(viewTag==2)
        return;
    [self showSearch];
    [self transitionFromViewController:currentViewController toViewController:secondViewController duration:0 options:0 animations:^{
    }  completion:^(BOOL finished) {
        currentViewController=secondViewController;
        viewTag=2;
        
    }];
    
}
-(void)ThirdBtnClick{
    if(viewTag==3)
        return;
    [self hiddenSearch];
    [self transitionFromViewController:currentViewController toViewController:thirdViewController duration:0 options:0 animations:^{
    }  completion:^(BOOL finished) {
        currentViewController=thirdViewController;
        viewTag=3;
        
    }];
}
-(void)FourthBtnClick{
    if(viewTag==4)
        return;
    [self hiddenSearch];
    [self transitionFromViewController:currentViewController toViewController:fourthViewController duration:0 options:0 animations:^{
    }  completion:^(BOOL finished) {
        currentViewController=fourthViewController;
        viewTag=4;
        
    }];
}

#pragma mark - 顶栏代理
- (void)clickLeft:(UIButton*)sender {
    
}
#pragma mark - 展开侧边栏
- (void)clickRight:(UIButton*)sender {
    [[SliderBar createSliderBar]showSideBarInViewController:self];
    
}

#pragma mark - 显示地址搜索框
- (void)showSearch {
    searchCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 64)];
    searchCoverView.backgroundColor = AIR_GREEN;
    [self.view addSubview:searchCoverView];
    
    mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 22, 320, 40)];
    mySearchBar.delegate = self;
    [mySearchBar setShowsCancelButton:NO];
    if (IOS_7) {
        mySearchBar.searchBarStyle = UISearchBarStyleMinimal;
    }
    mySearchBar.translucent = YES;
    
    //searchbar白色背景
    backView = [[UIView alloc]initWithFrame:CGRectMake(7, 30, 306, 28)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = 5;
    [self.view addSubview:backView];
    [self.view addSubview:mySearchBar];
    [mySearchBar setPlaceholder:@"搜索地点"];
    searchResults = [[NSMutableArray alloc]init];
    resultlatitude = [[NSMutableArray alloc]init];
    resultlongitude = [[NSMutableArray alloc]init];
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:mySearchBar contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.searchResultsTableView.rowHeight = 60;
    searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    if (IOS_7) {
        searchDisplayController.searchResultsTableView.separatorInset = UIEdgeInsetsZero;
    }
    //百度POI搜索
    searchPlace = [[BMKSearch alloc]init];
    searchPlace.delegate = self;
    
}

- (void)hiddenSearch {
    [mySearchBar removeFromSuperview];
    [searchCoverView removeFromSuperview];
    [backView removeFromSuperview];
    backView = nil;
    mySearchBar.delegate = nil;
    mySearchBar = nil;
    searchPlace.delegate = nil;
    searchPlace = nil;
    searchDisplayController = nil;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    ResultCell *cell = (ResultCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ResultCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.resultTitle.text = ((BMKPoiInfo*)searchResults[indexPath.row]).name;
    cell.resultSubtitle.text = ((BMKPoiInfo*)searchResults[indexPath.row]).address;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //释放搜索栏
    [searchDisplayController setActive:NO animated:YES];
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){((NSString*)resultlatitude[indexPath.row]).doubleValue, ((NSString*)resultlongitude[indexPath.row]).doubleValue};

    dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
        NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryPOIByPhone:[LRUserManager createManager].userPhone AndLongitude:((NSString*)resultlongitude[indexPath.row]) AndLatitude:((NSString*)resultlatitude[indexPath.row])];
        if ([[resposeDic objectForKey:@"code"] intValue]==0) {
            annotationArray = [resposeDic objectForKey:@"contents"];
        }
        dispatch_async (dispatch_get_main_queue(),^{
            
            if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"查询成功"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
                if (annotationArray.count!=0) {
                    for (NSDictionary *tempDic in annotationArray) {
                        BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
                        CLLocationCoordinate2D coor;
                        coor.latitude = [((NSArray*)[tempDic objectForKey:@"location"])[1] floatValue];
                        coor.longitude = [((NSArray*)[tempDic objectForKey:@"location"])[0] floatValue];
                        annotation.coordinate = coor;
                        if ([tempDic objectForKey:@"pm"]!=nil&&secondViewController.dataType==0) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"pm"]];
                            [secondViewController addAnnotationByCoordinate:pt AndName:annotation.title];
                        } else if ([tempDic objectForKey:@"co2"]!=nil&&secondViewController.dataType==1) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"co2"]];
                            [secondViewController addAnnotationByCoordinate:pt AndName:annotation.title];
                        } else if ([tempDic objectForKey:@"hcho"]!=nil&&secondViewController.dataType==2) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"hcho"]];
                            [secondViewController addAnnotationByCoordinate:pt AndName:annotation.title];
                        }
                        
                        
                    }
                }

            } else {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"查询失败,请稍后再试"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
            }
            
        });
    });
    
}

#pragma mark - UISearchDisplayDelegate -

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    
    searchDisplayController.searchContentsController.view.frame = CGRectMake(searchDisplayController.searchContentsController.view.frame.origin.x, searchDisplayController.searchContentsController.view.frame.origin.y, 385, searchDisplayController.searchContentsController.view.frame.size.height);
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    searchDisplayController.searchContentsController.view.frame = CGRectMake(searchDisplayController.searchContentsController.view.frame.origin.x, searchDisplayController.searchContentsController.view.frame.origin.y, 320, searchDisplayController.searchContentsController.view.frame.size.height);
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    searchCurPage = 0;
    //城市内检索，请求发送成功返回YES，请求发送失败返回NO
    NSString *cityStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCity"];
    if (cityStr.length ==0) {
        cityStr = DEFAULT_CITY;
    }
    
	BOOL flag = [searchPlace poiSearchInCity:cityStr withKey:searchText pageIndex:searchCurPage];
	if (flag) {
		NSLog(@"搜索成功");
	} else {
        NSLog(@"搜索失败");
    }
    
}

#pragma mark - BMKPoiSearchDelegate 模糊搜索回调

- (void)onGetPoiResult:(BMKSearch*)searcher result:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    [searchResults removeAllObjects];
    if (error == BMKErrorOk) {
		BMKPoiResult* result = [poiResultList objectAtIndex:0];
		for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            
            NSLog(@"搜索结果%@",poi.name);
            [resultlatitude addObject:[NSString stringWithFormat:@"%f",poi.pt.latitude]];
            [resultlongitude addObject:[NSString stringWithFormat:@"%f",poi.pt.longitude]];
            [searchResults addObject:poi];
		}
        [self.searchDisplayController.searchResultsTableView reloadData];
        
	} else if (error == BMKErrorRouteAddr){
        NSLog(@"起始点有歧义");
    } else {
        
    }
}
@end
